import {app, ipcMain, BrowserWindow, Menu, dialog, shell} from 'electron'
// import { createRequire } from 'node:module'
import {fileURLToPath} from 'node:url'
import path from 'node:path'

// const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null

function createMenu() {
    const template: Electron.MenuItemConstructorOptions[] = [
        {
            label: '编辑',
            submenu: [
                {
                    label: "新建公式",
                    accelerator: 'Ctrl+N',
                    click: () => {
                        const mainWindow = BrowserWindow.getFocusedWindow()
                        mainWindow?.webContents.send('menu-new-formula')
                    }
                }, {
                    label: "保存公式",
                    accelerator: 'Ctrl+S',
                    click: () => {
                        const mainWindow = BrowserWindow.getFocusedWindow()
                        mainWindow?.webContents.send('menu-save-formula')
                    }
                }, {
                    type: 'separator'
                }, {
                    label: "退出",
                    accelerator: process.platform === 'darwin' ? 'Cmd+Q' : 'Ctrl+D',
                    click: () => {
                        app.quit()
                    }
                }
            ]
        }, {
            label: '编辑',
            submenu: [
                {label: '撤销', accelerator: 'Ctrl+Z', role: 'undo'},
                {label: '重做', accelerator: 'Shift+Ctrl+Z', role: 'redo'},
                {type: 'separator'},
                {label: '剪切', accelerator: 'Ctrl+X', role: 'cut'},
                {label: '复制', accelerator: 'Ctrl+C', role: 'copy'},
                {label: '粘贴', accelerator: 'Ctrl+V', role: 'paste'},
                {label: '全选', accelerator: 'Ctrl+A', role: 'selectAll'},
            ]
        }, {
            label: '试图',
            submenu: [
                {label: '重新加载', accelerator: 'Ctrl+R', role: 'reload'},
                {label: '强制重新加载', accelerator: 'Ctrl+Shift+R', role: 'forceReload'},
                {label: '切换开发者工具', accelerator: 'F12', role: 'toggleDevTools'},
                {type: 'separator'},
                {label: '实际大小', accelerator: 'Ctrl+0', role: 'resetZoom'},
                {label: '放大', accelerator: 'Ctrl+=', role: 'zoomIn'},
                {label: '缩小', accelerator: 'Ctrl+-', role: 'zoomOut'},
                {type: 'separator'},
                {label: '全屏', accelerator: 'F11', role: 'togglefullscreen'},
            ]
        }, {
            label: '工具',
            submenu: [
                {
                    label: '手写公式识别',
                    accelerator: 'Ctrl+I',
                    click: () => {
                        const mainWindow = BrowserWindow.getFocusedWindow()
                        mainWindow?.webContents.send('menu-open-ocr')
                    }
                }, {
                    label: '打开公式库',
                    accelerator: 'Ctrl+O',
                    click: () => {
                        const mainWindow = BrowserWindow.getFocusedWindow()
                        mainWindow?.webContents.send('menu-open-library')
                    }
                }
            ]
        }, {
            label: '帮助',
            submenu: [
                {
                    label: '关于',
                    click: () => {
                        dialog.showMessageBox(BrowserWindow.getFocusedWindow()!, {
                            title: '关于',
                            message: '数学公式编辑器',
                            detail: '本软件基于 Electron 和 Vue 开发的数学公式编辑器\n版本: 1.0.0\n作者:Boxy'
                        })
                    }
                }, {
                    label: '学习 LaTeX',
                    click: () => {
                        shell.openExternal('https://en.wikibooks.org/wiki/LaTeX/Mathematics')
                    }
                }, {
                    label: '项目主页',
                    click: () => {
                        shell.openExternal('https://gitee.com/bxy_2000/formula-editor')
                    }
                }
            ]
        }
    ]

    if (process.platform === 'darwin') {
        template.unshift({
            label: '数学公式编辑器',
            submenu: [
                {label: '关于数学公式编辑器', role: 'about'},
                {type: 'separator'},
                {label: '服务', role: 'services', submenu: []},
                {type: 'separator'},
                {label: '隐藏数学公式编辑器', accelerator: 'Command+H', role: 'hide'},
                {label: '隐藏其他', accelerator: 'Command+Shift+H', role: 'hideOthers'},
                {label: '显示全部', role: 'unhide'},
                {type: 'separator'},
                {label: '退出', accelerator: 'Command+Q', click: () => app.quit()}
            ]
        })
    }

    const menu = Menu.buildFromTemplate(template)
    Menu.setApplicationMenu(menu)
}

function createWindow() {
    win = new BrowserWindow({
        width: 990,
        height: 770,
        title: '数学公式编辑器',
        icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.mjs'),
            nodeIntegration: false,
            contextIsolation: true,
        },
    })

    // Test active push message to Renderer-process.
    // win.webContents.on('did-finish-load', () => {
    //     win?.webContents.send('main-process-message', (new Date).toLocaleString())
    // })

    if (VITE_DEV_SERVER_URL) {
        win.loadURL(VITE_DEV_SERVER_URL)
    } else {
        // win.loadFile('dist/index.html')
        win.loadFile(path.join(RENDERER_DIST, 'index.html'))
    }

    // 如果需要动态修改标题，可以这样
    win.on('page-title-updated', (event) => {
        // 阻止网页修改标题
        event.preventDefault()
    })
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
        win = null
    }
})

app.on('activate', () => {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow()
    }
})

app.whenReady().then(() => {
    createMenu()
    createWindow()
})


// 窗口控制
ipcMain.handle('set-title', (event, title: string) => {
    const webContents = event.sender
    const win = BrowserWindow.fromWebContents(webContents)
    win?.setTitle(title)
})

ipcMain.handle('minimize-window', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    win?.minimize()
})

ipcMain.handle('maximize-window', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    if (win?.isMaximized()) {
        win.unmaximize()
    } else {
        win?.maximize()
    }
})

ipcMain.handle('close-window', (event) => {
    const win = BrowserWindow.fromWebContents(event.sender)
    win?.close()
})
